"use strict";

var Router = require('koa-router');
var config = require('../../../config/config.js');
var dao = require('../../../dao/mongo/category.js');
var debug = require('debug')('category');

console.log('router:' + config.baseUrl + '/v1/category');
var router = new Router({
    prefix: config.baseUrl + '/v1/category'
});

router.get('/test', function*() {
    this.body = 'test work fine';
});

//router.get('/:id', function*() {
//  var result = yield dao.findById(this.params.id);
//  this.body = result;
//});

router.get('/', function*() {
    var inParams = this.request.inParams;
    var result;
    if (inParams.id) {
        result = yield dao.findById(inParams.id);
    } else if (typeof inParams.level !== 'undefined') {
        result = yield dao.findByLevel(inParams.level);
    } else if (inParams.pid) {
        if (inParams.pid === 'null') {
            result = yield dao.findByLevel(1);
        } else {
            result = yield dao.findByPid(inParams.pid);
        }
    }
    this.body = result;
});

/**
 * name:xx
 * pid:xx
 */
router.post('/', function*() {
    var result = yield dao.save(this.request.inParams);
    this.body = result;
});

/**
 * import category tree
 *
 */
router.post('/batch', function*() {
    var result = yield dao.saveMany(this.request.inParams);
    this.body = result;
});

router.delete('/:id', function*() {
    var result = yield dao.deleteById(this.params.id);
    this.body = result;
});


router.post('/tree', function*() {
    var result = yield dao.saveTree(this.request.inParams);
    this.body = result;
});

module.exports = router.routes();